package broker.yahooJapanAuction;

import com.google.api.translate.Language;
import com.google.api.translate.Translator;
import java.io.File;
import java.net.URL;
import java.util.Calendar;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import model.Data;
import model.DateTime;
import model.db.table.Bid;
import model.db.table.BidHistory;

/**
 * Author: Raoux Etienne
 * Student login: jc218934
 * Student number: 12448190
 * email: etienne.raoux@my.jcu.edu.au
 * alt email: jc218934@gmail.com
 */
public class UrlExtractorFromList extends Thread
{
    HtmlSourceReaderToList reader;
    private ArrayList<String> itemList;
    private ArrayList<String> itemHistoryList;


    private ArrayList<BidHistory> bidHistoryList;
    private final UrlExtractorListener listener;
    private final String url;
    public UrlExtractorFromList(UrlExtractorListener listener, String url)
    {
        bidHistoryList = new ArrayList<BidHistory>();
        this.listener = listener;
        this.url = url;
        
    }

    @Override
    public void run()
    {
        try
        {
            int itemId = BidHistory.selectNextId();
            reader = new HtmlSourceReaderToList();
            itemList = reader.readProducts(url);

            System.out.println("extract information and display it");

            for (String auctionUrl:itemList)
            {
                String imgUrl = extractImageUrlFromString(auctionUrl);
                String newImgUrl = Data.imgFolder+itemId+".jpg";
                ImageIO.write(ImageIO.read(new URL(imgUrl)) , "jpg", new File(newImgUrl));

                imgUrl = newImgUrl;

                String title = extractTitleFromString(auctionUrl);
                String itemUrl = extractItemDescriptionUrlFromString(auctionUrl);
                String sellerUrl = extractSellerUrlFromString(auctionUrl);
                String sellerName = extractSellerFromString(auctionUrl);
                Double price = extractPriceFromString(auctionUrl);
                String biddingHistoryUrl = extractItemBiddingHistoryUrlFromString(auctionUrl);
                BidHistory bidHistory = new BidHistory(itemId++, imgUrl, title, itemUrl, sellerUrl,
                        sellerName, price, new ArrayList <Bid>());
                downloadAndExtractHistory(biddingHistoryUrl, bidHistory);
                
                bidHistoryList.add(bidHistory);
                listener.addItem(bidHistory);
            }
        }
        catch (Exception ex)
        {
            System.out.println("UrlextractorFromList "+ex);
        }
    }

    private String extractImageUrlFromString(String str)
    {
        return extractInfo("><img src=\"", "\"", str);
    }

    private String extractTitleFromString(String str)
    {
        str = extractInfo("\" alt=\"", "\"", str);
        Translator translator = new Translator();
        String response = translator.translate(str, Language.JAPANESE, Language.ENGLISH);
        if (response == null) return str;
        return response;
    }

    private String extractItemDescriptionUrlFromString(String str)
    {
        return extractInfo("http://ord.yahoo.co.jp/o/auction/SIG", "\"", str, true, false);
    }

    private String extractSellerUrlFromString(String str)
    {
        str = extractInfoFrom("<div class=\"a4 cf\"><p>" ,str);
        return extractInfo("<a href=\"","\"", str);
    }

    private String extractSellerFromString(String str)
    {
        str = extractInfoFrom("<div class=\"a4 cf\"><p>" ,str);
        return extractInfo("\">","</a>", str);
    }

    private Double extractPriceFromString(String str)
    {
        String tmpStr = extractInfo("<td class=\"pr1\">","円", str);
        tmpStr = tmpStr.replaceAll(",", "");

        return Double.parseDouble(tmpStr);
    }

    private String extractItemBiddingHistoryUrlFromString(String str)
    {
        String start = "<td class=\"bi\"><a href=\"";

        if (!str.contains(start))
        {
            return null;
        }
        else
        {
            return extractInfo(start,"\"", str);
        }
    }

    private String extractInfo(String from, String to, String str, boolean fromIncluded, boolean toIncluded)
    {
        try
        {
            str = fromIncluded ? str.substring(str.indexOf(from)) : str.substring(str.indexOf(from)+from.length());
            str = toIncluded ? str.substring(0, str.indexOf(to)+to.length()) : str.substring(0, str.indexOf(to));
            return str;
        }
        catch (Exception ex)
        {
            System.out.println(str);
            return "";
        }
    }

    private String extractInfo(String from, String to, String str)
    {
        return extractInfo(from, to, str, false, false);
    }

    private String extractInfoFrom (String from, String str, boolean fromIncluded)
    {
        return fromIncluded ? str.substring(str.indexOf(from)) : str.substring(str.indexOf(from)+from.length());
    }

    private String extractInfoFrom (String from, String str)
    {
        return extractInfoFrom (from, str, false);
    }

    private void downloadAndExtractHistory(String url, BidHistory bidHistory)
    {
        System.out.println("Downloading history");
        Thread thread = new Thread(new DownloadAndExtractHistoryThr(url, bidHistory));
        thread.start();
    }

    private class DownloadAndExtractHistoryThr implements Runnable
    {
        private final String url;
        private final BidHistory bidHistory;

        public DownloadAndExtractHistoryThr(String url, BidHistory bidHistory)
        {
            this.url = url;
            this.bidHistory = bidHistory;
        }
        public void run()
        {
            try
            {
                if (url.compareTo("null") == 0) return ;
                reader = new HtmlSourceReaderToList();
                ArrayList<String> bidList = reader.readHistory(url);
                for (String auctionHistory:bidList)
                {
                    try
                    {
                        DateTime dateTime = extractDateTimeOfBid(auctionHistory);
                        String bidder = extractBidderOfBid(auctionHistory);
                        String bidType = extractBidTypeOfBid(auctionHistory);
                        Integer qty;
                        Double amt;
                        if(bidType.compareTo("automatic") == 0)
                        {
                            qty = 1;
                            amt = Double.parseDouble(extractAmtOfBid(auctionHistory));
                        }
                        else
                        {
                            qty = Integer.parseInt(extractQtyOfBid(auctionHistory));
                            amt = Double.parseDouble(extractAmtOfBidWithQty(auctionHistory));
                        }
                        bidHistory.add(new Bid(bidHistory.getItemId(), dateTime.getDate(), bidder, bidType, qty, amt));
                    }
                    catch (Exception ex)
                    {
                        //ex.printStackTrace();
                    }
                }
            }
            catch (Exception ex)
            {
                //ex.printStackTrace();
            }
            bidHistory.insertInDb();
        }
    }

    private DateTime extractDateTimeOfBid(String str)
    {
        String start = "<tr><td class=\"decBg01\">[";
        String tmpStr;
        str = str.substring(str.indexOf(start)+start.length());
        tmpStr = str.substring(0, str.indexOf("��"));
        int month = Integer.parseInt(tmpStr);
        str = str.substring(str.indexOf("��")+"��".length()+1);
        tmpStr = str.substring(0, str.indexOf("��"));
        int day = Integer.parseInt(tmpStr.replaceAll(" ", ""));
        str = str.substring(str.indexOf("��")+"��".length()+1);
        tmpStr = str.substring(0, str.indexOf("��"));
        int hour = Integer.parseInt(tmpStr);
        str = str.substring(str.indexOf("��")+"��".length()+1);
        tmpStr = str.substring(0, str.indexOf("ʬ"));
        int min = Integer.parseInt(tmpStr);
        Calendar cal = Calendar.getInstance();
        cal.set(2011, month -1, day, hour, min);
        DateTime dateTime = new DateTime(cal.getTimeInMillis());
        return dateTime;
    }

    private String extractBidderOfBid(String str)
    {
        return extractInfo("] "," ", str);
    }

    private String extractBidTypeOfBid(String str)
    {
        if (str.contains("オークション開始")) return "auction start";
        if (str.contains("��ư������")) return "automatic";
        return "manual";
    }

    private String extractQtyOfBid(String str)
    {
        return extractInfo("���������̡� "," �� ", str);
    }

    private String extractAmtOfBid(String str)
    {
        return extractInfo("��ư������ ","</td>", str).replaceAll(",", "");
    }

    private String extractAmtOfBidWithQty(String str)
    {
        return extractInfo(" �� ","</td>", str).replaceAll(",", "");
    }
}
